<script setup lang="ts">
import { useUserStore } from "~/store/useUser";
import { buyerCommentPage, getSalesBaseInfo, buyerIndex, buyerIndexComment } from "~/api/user";
import { useImageCache } from "~/composables/useImageCache";

useSeoMeta({
  title: "我的主页 - 技能猴子",
  ogTitle: "我的主页 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const { getCoverImage, preloadImages, imageUrlCache } = useImageCache();

const userInfo = ref({});
onMounted(() => {
  const user = useUserStore();
  userInfo.value = user.getUserInfo;
  params.value.buyerUserId = userInfo.value.userId;
  getUserInfo();
  getComment();
});

// 获取买家个人信息
const buyerInfo = ref({});
const getUserInfo = async () => {
  try {
    const res = await buyerIndex();
    const data = res.data;
    
    // 处理 avatar 字段，如果是 OSS ID，则加载 OSS 图片
    if (data.avatar && typeof data.avatar === 'string' && !data.avatar.includes('http')) {
      // 是 OSS ID，预加载图片 URL
      await preloadImages([data.avatar]);
      // 从缓存中获取或使用 getCoverImage
      const cachedUrl = imageUrlCache.value?.[data.avatar];
      data.avatar = cachedUrl || getCoverImage(data.avatar);
    }
    
    buyerInfo.value = data;
  } catch (err) {
    console.log(err);
  }
};

// 获取评论列表、分页
const params = ref<{
  pageNum: number;
  pageSize: number;
  buyerUserId: string;
  orderBy: number;
  type?: number | 0;
}>({
  pageNum: 1,
  pageSize: 10,
  buyerUserId: "",
  orderBy: 0,
  type: 0,
});
const totalCount = ref(0);
const commentList = ref([]);
const goodCount = ref(0);
const neutralCount = ref(0);
const negativeCount = ref(0);
const activeSort = (type: number) => {
  console.log(type);
  params.value.orderBy = type;
  params.value.pageNum = 1;
  console.log(params.value.orderBy);
  getComment();
};
const getComment = async () => {
  try {
    const { data } = await buyerIndexComment(params.value);
    const records = data.commentInfoList?.records || [];
    
    // 收集所有需要预加载的 OSS ID（包括 picArray 和 buyerAvatar）
    const allOssIds: string[] = [];
    records.forEach((item: any) => {
      // 收集 picArray 中的 OSS ID
      if (item.picArray && Array.isArray(item.picArray)) {
        item.picArray.forEach((pic: any) => {
          if (pic.ossId) {
            allOssIds.push(pic.ossId);
          }
        });
      }
      // 收集 buyerAvatar 的 OSS ID
      if (item.buyerAvatar && typeof item.buyerAvatar === 'string' && !item.buyerAvatar.includes('http')) {
        allOssIds.push(item.buyerAvatar);
      }
      // 收集 buyerProfile 的 OSS ID（如果存在）
      if (item.buyerProfile && typeof item.buyerProfile === 'string' && !item.buyerProfile.includes('http')) {
        allOssIds.push(item.buyerProfile);
      }
    });
    
    // 批量预加载图片 URL
    if (allOssIds.length > 0) {
      await preloadImages(allOssIds);
    }
    
    // 处理 picArray 和 buyerAvatar，将 OSS ID 转换为图片 URL
    // 由于已经批量预加载，可以直接从缓存中获取，或使用 getCoverImage 处理
    const processedRecords = records.map((item: any) => {
      const processedItem: any = { ...item };
      
      // 处理 picArray
      if (item.picArray && Array.isArray(item.picArray)) {
        const picUrls = item.picArray.map((pic: any) => {
          if (pic.ossId) {
            // 优先从缓存中获取 URL（批量预加载后应该已经在缓存中）
            const cachedUrl = imageUrlCache.value?.[pic.ossId];
            if (cachedUrl) {
              return cachedUrl;
            }
            // 如果缓存中没有，使用 getCoverImage（会返回默认图片并异步加载）
            return getCoverImage(pic.ossId);
          }
          // 如果已经是 URL 字符串，直接返回
          if (typeof pic === 'string') {
            return pic;
          }
          // 其他格式，返回空字符串
          return '';
        }).filter(url => url); // 过滤掉空值
        
        processedItem.picArray = picUrls;
      }
      
      // 处理 buyerAvatar
      if (item.buyerAvatar) {
        if (typeof item.buyerAvatar === 'string' && !item.buyerAvatar.includes('http')) {
          // 是 OSS ID，从缓存中获取或使用 getCoverImage
          const cachedUrl = imageUrlCache.value?.[item.buyerAvatar];
          processedItem.buyerAvatar = cachedUrl || getCoverImage(item.buyerAvatar);
        } else {
          // 已经是 URL，直接使用
          processedItem.buyerAvatar = item.buyerAvatar;
        }
      }
      
      // 处理 buyerProfile（如果存在且是 OSS ID）
      if (item.buyerProfile && typeof item.buyerProfile === 'string' && !item.buyerProfile.includes('http')) {
        const cachedUrl = imageUrlCache.value?.[item.buyerProfile];
        processedItem.buyerProfile = cachedUrl || getCoverImage(item.buyerProfile);
      }
      
      return processedItem;
    });
    
    commentList.value = processedRecords;
    
    if (!totalCount.value) {
      totalCount.value = Number(data.commentInfoList?.total || 0);
      goodCount.value = data.goodCommentCount || 0;
      neutralCount.value = data.mediumCommentCount || 0;
      negativeCount.value = data.badCommentCount || 0;
    }
  } catch (e) {
    console.log(e);
  }
};
const getCommentTypeList = (type: number) => {
  params.value.type = type;
  if (type === 0) {
    params.value.type = 0;
  }
  params.value.pageNum = 1;
  getComment();
};
const currentChange = (e) => {
  params.value.pageNum = e;
  getComment();
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="my-home-page">
    <div class="my-data">
      <div class="user">
        <el-image class="head" :src="buyerInfo.avatar || userInfo.avatar" alt="">
          <template #error>
            <img class="default-head" src="~/assets/app-mj.png" alt="" />
          </template>
        </el-image>
        <div class="info">
          <p class="name">
            <span class="name-text">{{ buyerInfo.nickName || userInfo.nickName }}</span>
            <span class="lv">VIP{{ buyerInfo.level || 1 }}</span>
          </p>
          <p class="address" v-if="buyerInfo.companyName">
            {{ buyerInfo.companyName }}
          </p>
        </div>
      </div>
      <div class="data-info">
        <div class="info-item">
          <img class="info-icon" src="~/assets/user-data-1.png" alt="" />
          <div class="info-text">
            <span class="title">买家等级</span>
            <span class="user-num">{{ buyerInfo.level || 1 }}级</span>
          </div>
        </div>
        <div class="line"></div>
        <div class="info-item">
          <img class="info-icon" src="~/assets/user-data-2.png" alt="" />
          <div class="info-text">
            <span class="title">购买订单总数</span>
            <span class="user-num">{{ buyerInfo.buyOrderNum || 0 }}</span>
          </div>
        </div>
        <div class="line"></div>
        <div class="info-item">
          <img class="info-icon" src="~/assets/user-data-3.png" alt="" />
          <div class="info-text">
            <span class="title">总好评数</span>
            <span class="user-num">{{ buyerInfo.favorCommentCount || 0 }}</span>
          </div>
        </div>
        <div class="line"></div>
        <div class="info-item">
          <img class="info-icon" src="~/assets/user-data-4.png" alt="" />
          <div class="info-text">
            <span class="title">好评率</span>
            <span class="user-num">{{ (buyerInfo.favorRate || 0).toFixed(1) }}%</span>
          </div>
        </div>
      </div>
    </div>
    <div class="evaluate-list">
      <div class="evaluate-box">
        <div class="header">
          <p class="title">获得评价（{{ totalCount || 0 }}）</p>
          <div class="sort-box">
            <p class="filter">
              <span :class="{ active: !params.type }" @click="getCommentTypeList(0)"
                >全部({{ totalCount || 0 }})</span
              >
              <span :class="{ active: params.type === 1 }" @click="getCommentTypeList(1)"
                >好评({{ goodCount || 0 }})</span
              >
              <span :class="{ active: params.type === 2 }" @click="getCommentTypeList(2)"
                >中评({{ neutralCount || 0 }})</span
              >
              <span :class="{ active: params.type === 3 }" @click="getCommentTypeList(3)"
                >差评({{ negativeCount || 0 }})</span
              >
            </p>
            <div class="sort">
              <span :class="{ active: params.orderBy === 0 }" @click="activeSort(0)"
                >默认排序</span
              >
              <span :class="{ active: params.orderBy === 1 }" @click="activeSort(1)"
                >最新评价</span
              >
            </div>
          </div>
        </div>
        <template v-if="commentList.length">
          <MyEvaluationItem v-for="item of commentList" :key="item.id" :itemData="item" />
        </template>
        <el-empty v-else description="暂无评论"></el-empty>
        <div class="paging-box">
          <el-pagination
            layout="prev, pager, next"
            :page-size="params.pageSize"
            :total="totalCount"
            @currentChange="currentChange"
          />
        </div>
      </div>
    </div>
  </div>
  <BaseFooter />
</template>

<style scoped lang="scss">
.my-home-page {
  background: #f9f9f9;
  padding-top: 80px;
}
.my-data {
  width: 1104px;
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin: 32px auto;
  display: flex;
  padding: 32px 24px;
  box-sizing: border-box;
  .user {
    flex: 1;
    display: flex;
    align-items: center;
    .head {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-right: 12px;
    }
    .default-head {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-right: 12px;
    }
    .info {
      flex: 1;
      .name {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
      }
      .name-text {
        font-size: 20px;
        color: #191e28;
        font-weight: bold;
        margin-right: 16px;
      }
      .lv {
        color: #1dbf73;
        background: rgba(29, 191, 115, 0.08);
        border-radius: 4px 4px 4px 4px;
        font-size: 12px;
        font-weight: bold;
        padding: 2px 8px;
      }
      .address {
        color: rgba(25, 30, 40, 0.48);
      }
    }
  }
  .data-info {
    display: flex;
    align-items: center;
    .info-item {
      display: flex;
      align-items: center;
      padding: 0 25px;
      .info-icon {
        width: 36px;
        height: 36px;
        margin-right: 12px;
      }
      .info-text {
        display: flex;
        flex-direction: column;
        .title {
          font-size: 12px;
          color: rgba(25, 30, 40, 0.48);
          margin-bottom: 12px;
        }
        .user-num {
          font-size: 18px;
          color: #191e28;
          font-weight: bold;
          span {
            font-size: 14px;
          }
        }
      }
    }
    .line {
      width: 1px;
      height: 40px;
      background: rgba(25, 30, 40, 0.08);
    }
  }
}
.evaluate-list {
  background: #fff;
  padding-bottom: 32px;
  padding-top: 48px;
  .evaluate-box {
    width: 1100px;
    margin: 0 auto;
  }
  .header {
    .title {
      color: #191e28;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .sort-box {
      display: flex;
      align-items: center;
      span {
        line-height: 12px;
        cursor: pointer;
        &:nth-child(1) {
          padding-right: 12px;
          margin-right: 12px;
          border-right: 1px solid rgba(25, 30, 40, 0.08);
        }
      }
      .sort {
        color: #191e28;
        .active {
          color: #1dbf73;
          font-weight: bold;
        }
      }
    }
    .filter {
      flex: 1;
      margin-bottom: 20px;
      span {
        padding: 4px 8px;
        color: rgba(25, 30, 40, 0.6);
        background: rgba(25, 30, 40, 0.02);
        border-radius: 6px 6px 6px 6px;
        margin-right: 12px;
        &.active {
          color: #1dbf73;
          background: rgba(29, 191, 115, 0.08);
        }
      }
    }
  }
}
.paging-box {
  display: flex;
  justify-content: center;
  padding-bottom: 16px;
  padding-top: 32px;
}
</style>
